package com.dc.base.ui.activity;

import android.view.LayoutInflater;
import android.view.View;

import androidx.viewbinding.ViewBinding;

import com.dc.base.viewmodel.BaseViewModel;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;

/**
 * @author 冰柠檬dc
 */
public abstract class BaseVmVbActivity<VM extends BaseViewModel, VB extends ViewBinding> extends BaseVmActivity<VM> {

    protected VB viewBinding;

    @Override
    protected int layoutId() {
        return 0;
    }

    @Override
    protected View initDataBind() {
        viewBinding = getViewBinding();
        return viewBinding == null ? null : viewBinding.getRoot();
    }

    protected VB getViewBinding() {
        ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
        Class cls = (Class) type.getActualTypeArguments()[1];
        try {
            Method inflate = cls.getDeclaredMethod("inflate", LayoutInflater.class);
            return  (VB) inflate.invoke(null, getLayoutInflater());
        } catch (NoSuchMethodException | IllegalAccessException| InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 非反射获取VB(子类中实现，如ActivityMainBinding.inflate(getLayoutInflater()))
     */
//    protected abstract VB getViewBinding();
}
